package com.zcbl.toolkit.http.util;

import com.zcbl.toolkit.exception.SystemRuntimeException;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;

import javax.servlet.ServletOutputStream;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author he peng
 * @create 2018/4/10 17:47
 * @see
 */
public class HttpResponseUtils {

    private HttpResponseUtils() {}

    public static ServletOutputStream getOutputStreamQuiet(ServletResponse response) {
        Assert.notNull(response , "response == null");
        ServletOutputStream outputStream;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            throw new SystemRuntimeException(e.getMessage() , e);
        }
        return outputStream;
    }

    public static void writeJson(ServletResponse response , String content) {
        Assert.notNull(response , "response == null");
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
        PrintWriter printWriter = new PrintWriter(getOutputStreamQuiet(response));
        printWriter.write(content);
        printWriter.flush();
    }
}
